//
//  ABCDynamicUpdater.m
//  ABCAppearanceKit_Example
//
//  Created by mac on 2022/9/1.
//  Copyright © 2022 Joe. All rights reserved.
//

#import "ABCDynamicUpdater.h"
#import "NSObject+ABCDynamic.h"

@interface ABCDynamicUpdater ()

@property (nonatomic, strong) NSHashTable *targetSet;

@end

@implementation ABCDynamicUpdater

+ (instancetype)sharedInstance {
    static ABCDynamicUpdater *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[ABCDynamicUpdater alloc]init];
        manager.targetSet = [NSHashTable weakObjectsHashTable];
    });
    return manager;
}

- (void)abc_addDynamicTarget:(__kindof NSObject *)target {
    if ([self.targetSet containsObject:target]) {
        return;
    }
    [self.targetSet addObject:target];
}

- (void)abc_removeDynamicTarget:(__kindof NSObject *)target {
    if (![self.targetSet containsObject:target]) {
        return;
    }
    [self.targetSet removeObject:target];
}

- (void)abc_updateDynamicStyle:(ABCAppearanceDynamicStyle)dynamicStyle {
    [self.targetSet.allObjects enumerateObjectsUsingBlock:^(NSObject *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj && obj.updateDynamicList && obj.updateDynamicList.count > 0) {
            [obj.updateDynamicList enumerateObjectsUsingBlock:^(ABCUpdateDynamicBlock  _Nonnull dynamicBlock, NSUInteger idx, BOOL * _Nonnull stop) {
                if (![NSThread isMainThread]) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        dynamicBlock(dynamicStyle);
                    });
                } else {
                    dynamicBlock(dynamicStyle);
                }
            }];
        }
    }];
}



@end
